#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "stackADT.h"

void InitializeStack(SeqStack *stack, int size)
{
    stack->data = (ElementType *)malloc(sizeof(ElementType) * size);
    stack->currentSize = 0;
    stack->stackSize = size;
}

bool StackIsEmpty(SeqStack *stack)
{
    return stack->currentSize == 0 ? true : false;
    // 我感觉直接 return stack->currentSize == 0; 也可以
}

bool StackIsFull(SeqStack *stack)
{
    return stack->stackSize == stack->currentSize ? true : false;
}

int StackItemCount(SeqStack *stack)
{
    return stack->currentSize;
}

bool GetstackSizeOfStack(SeqStack *pstack, ElementType *elem)
{
    if (StackIsEmpty(pstack))
    {
        puts("Stack is Empty!\n");
        return false;
    }
    *elem = pstack->data[pstack->currentSize - 1];
    return true;
}

bool PushStack(SeqStack *pstack, ElementType *elem)
{
    // 重新开辟空间
    if (pstack->currentSize == pstack->stackSize)
    {
        pstack->data = (ElementType *)realloc(pstack->data, (pstack->stackSize + 1) * sizeof(ElementType));
        // 重新分配内存
        if (!pstack->data)
        {
            puts("realloc() error!");
            return false;
        }
        ++pstack->stackSize;
        printf("realloc() success! StackSize + 1! currentSize is %d \n", pstack->stackSize);
    }
    pstack->data[pstack->currentSize] = *elem;
    pstack->currentSize++;
    return true;
}

bool PopStack(SeqStack *pstack, ElementType *elem)
{
    if (StackIsEmpty(pstack))
    {
        puts("Stack is Empty!\n");
        return false;
    }

    *elem = pstack->data[--pstack->currentSize];
    return true;
}

ElementType* GetTopOfStack(SeqStack *pstack){
    return &(pstack->data[pstack->currentSize -1]);
}

bool ListStack(SeqStack *pstack)
{
    if (StackIsEmpty(pstack))
    {
        puts("Stack is empty!");
        return false;
    }
    for (size_t i = pstack->currentSize; i > 0; i--)
    {
        printf("%4d ", pstack->data[i - 1]);
    }
    printf("\n");
    return true;
}

bool EmptyStack(SeqStack *pstack)
{
    if (pstack->currentSize == 0)
    {
        printf("CurrentStack is Empty!\n");
        return false;
    }
    else
    {
        pstack->currentSize = 0;
        return true;
    }
}

